from django.db.models import Prefetch, Q
from datetime import datetime

from django.shortcuts import render
from rest_framework.permissions import AllowAny
from rest_framework.viewsets import ModelViewSet
from task.models import Task

from rest_framework import status
from rest_framework.decorators import action
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from group.models import Group
from group.serializers import GroupSerializer
from module.models import Module
from task.models import Task
from task.serializers import TaskSerializers, UserTaskSerializers
from user.models import User, UserTask
from user.serializers import UserSerializers


# Create your views here.
class UserTaskView(ModelViewSet):
    queryset = UserTask.objects.all()
    serializer_class = UserTaskSerializers

    # 分页
    pagination_class = PageNumberPagination
    PageNumberPagination.page_size_query_param = 'rows'

    def list(self, request, *args, **kwargs):
        # 获取查询参数
        stage_id = request.query_params.get('stage', None)
        module_id = request.query_params.get('module', None)
        level = request.query_params.get('level', None)
        search = request.query_params.get('search', None)

        user_id=request.user.id #获取当前用户的id

        # 获取当前用户的任务 的中间表,需要根据中间表  拿到任务具体的任务
        queryset = self.get_queryset().filter(user_id=user_id).prefetch_related('task')

        # 根据查询参数动态添加过滤条件
        task_queryset = queryset.all().values_list('task_id', flat=True).distinct()  # 获取当前用户所有任务的ID
        task_filter = Task.objects.filter(id__in=task_queryset)  # 基于这些ID过滤Task

        # 根据查询参数动态添加过滤条件
        if stage_id is not None:
            queryset = queryset.filter(stage_id=stage_id)
            if module_id is not None:
                queryset = queryset.filter(module_id=module_id)
        if level is not None:
            queryset = queryset.filter(level=level)
        # 关键字过滤
        if search:
            queryset = queryset.filter(Q(title__icontains=search))

        # 将过滤后的 Task ID 转换回 UserTask 查询集
        filtered_user_tasks = queryset.filter(task_id__in=task_filter.values_list('id', flat=True))

        # 进行分页
        paginate = self.paginate_queryset(filtered_user_tasks)
        if paginate is None:
            return Response(data={"message": "请求必须进行分页"}, status=status.HTTP_400_BAD_REQUEST)
        #序列化
        serializer = self.get_serializer(paginate, many=True)

        # 返回分页之后的结果
        return self.get_paginated_response(serializer.data)




class TaskView(ModelViewSet):
    queryset = Task.objects.all()
    serializer_class = TaskSerializers
    # 分页
    pagination_class = PageNumberPagination
    PageNumberPagination.page_size_query_param = 'rows'
    # 查询任务 接口
    # def list(self, request, *args, **kwargs):
    #     # 创建一个过滤后的 Module queryset，只获取未删除的模块
    #     modules_queryset = Module.objects.filter(is_delete=False)
    #     # 过滤 Stage 数据，确保只返回未删除的 Stage
    #     queryset = self.get_queryset().filter(is_delete=False)
    #     # 使用 Prefetch 来定制 Module 的查询，确保模块是未删除的
    #     queryset = queryset.prefetch_related(
    #         Prefetch('module', queryset=modules_queryset, to_attr='modules')
    #     )
    #     self.queryset = queryset
    #     return super().list(request, *args, **kwargs)

    def list(self, request, *args, **kwargs):
        # 获取查询参数
        stage_id = request.query_params.get('stage', None)
        module_id = request.query_params.get('module', None)
        level = request.query_params.get('level', None)
        search = request.query_params.get('search', None)

        # 获取未删除的任务
        queryset = self.get_queryset().filter(is_delete=False)

        # 根据查询参数动态添加过滤条件
        if stage_id is not None:
            queryset = queryset.filter(stage_id=stage_id)
            if module_id is not None:
                queryset = queryset.filter(module_id=module_id)
        if level is not None:
            queryset = queryset.filter(level=level)
        # 关键字过滤
        if search:
            queryset = queryset.filter(Q(title__icontains=search))
        # 进行分页
        paginate = self.paginate_queryset(queryset)
        if paginate is None:
            return Response(data={"message": "请求必须进行分页"}, status=status.HTTP_400_BAD_REQUEST)
        serializer = self.get_serializer(paginate, many=True)
        # 返回分页之后的结果
        return self.get_paginated_response(serializer.data)


    def destroy(self, request, *args, **kwargs):
        # 删除任务
        url = request.path
        id = url.rsplit("/")[-1]
        queryset = self.get_queryset().filter(id=id)
        if queryset:
            queryset.update(is_delete=True, update_time=datetime.now())
            return Response(data={"message": "删除成功"}, status=status.HTTP_200_OK)
        return Response(data={"message": "删除失败"}, status=status.HTTP_400_BAD_REQUEST)


    @action(methods=['GET'],detail=False,url_path='groupApplyPson',url_name='groupApplyPson')
    def groupApplyPson(self,request,*args,**kwargs):
        # 在任务中心中, 分配要查看的人员
        user=User.objects.all().filter(is_staff=False) #获取要分组的人员
        serializer=UserSerializers(user,many=True)
        if serializer.data:
            return Response(data=serializer.data,status=status.HTTP_200_OK)

    @action(methods=['POST'], detail=False, url_name='selectgroupApply', url_path='selectgroupApply')
    def selectgroupApply(self, request, *args, **kwargs):
        # 获取在任务列表添加的人员
        group_id = request.query_params.get('id')#获取要分配的组id
        group = Group.objects.get(id=group_id) #获取组对象
        user_ids = {int(key): int(value) for key, value in request.data.items()}  # 将QueryDict转换为字典，键为用户索引，值为用户ID
        for user_id in user_ids.values():
            user = User.objects.get(id=user_id)  # 获取被选中的用户
            group.users.add(user)  # 将用户添加到组中
        return Response(status=status.HTTP_200_OK)



class TaskViewSave(ModelViewSet): #创建新的任务
    queryset = Task.objects.all()
    serializer_class = TaskSerializers


    def create(self, request, *args, **kwargs):
        # 查询阶段名是否已添加
        queryset = self.get_queryset().filter(title=request.data['title'], is_delete=False)
        if queryset:
            return Response(data={"message": "任务名已存在"}, status=status.HTTP_400_BAD_REQUEST)

        serialize=self.get_serializer(data=request.data)
        serialize.is_valid(raise_exception=True)
        self.perform_create(serialize)
        headers = self.get_success_headers(serialize.data)
        return Response(data=serialize.data, status=status.HTTP_201_CREATED, headers=headers)

    @action(methods=['GET'],detail=False,url_path='task-update-show',url_name='task-update-show')
    def task_update_Show(self,request,*args,**kwargs):
        #修改任务
        task_id=request.query_params.get('id') #获取当前任务的id
        task_querySet=self.get_queryset().filter(id=task_id)
        serialize=self.get_serializer(task_querySet,many=True)
        if serialize.data:
            return Response(data=serialize.data,status=status.HTTP_200_OK)
        return Response(data={"message":'修改任务失败'},status=status.HTTP_404_NOT_FOUND)


    @action(methods=['POST'],detail=False,url_name='task-update',url_path='task-update')
    def update_task(self,request,*args,**kwargs):
        #修改数据
        print(request.data,"////////需要修改的数据")
